package com.shujia.custom.udtf;

import org.apache.hadoop.hive.ql.exec.UDFArgumentException;
import org.apache.hadoop.hive.ql.metadata.HiveException;
import org.apache.hadoop.hive.ql.udf.generic.GenericUDTF;
import org.apache.hadoop.hive.serde2.objectinspector.ObjectInspector;
import org.apache.hadoop.hive.serde2.objectinspector.ObjectInspectorFactory;
import org.apache.hadoop.hive.serde2.objectinspector.StructObjectInspector;
import org.apache.hadoop.hive.serde2.objectinspector.primitive.PrimitiveObjectInspectorFactory;

import java.util.ArrayList;

/*
    输入：a,1,2,3,4,5,6,7,8,9,10,11,12
    输出：
        a 0时 1
        a 2时 2
        a 4时 3
        ..
        a 24时 12

 */
public class MyUDTFDemo3 extends GenericUDTF {
    @Override
    public StructObjectInspector initialize(StructObjectInspector argOIs) throws UDFArgumentException {
        //创建一个List集合存储结果列的名字
        ArrayList<String> colNames = new ArrayList<>();
        //创建一个集合存储每一列的数据类型
        ArrayList<ObjectInspector> colTypes = new ArrayList<>();

        //向集合中添加元素，设置列的名字以及类型
        colNames.add("id");
        colTypes.add(PrimitiveObjectInspectorFactory.javaStringObjectInspector);
        colNames.add("time");
        colTypes.add(PrimitiveObjectInspectorFactory.javaStringObjectInspector);
        colNames.add("value");
        colTypes.add(PrimitiveObjectInspectorFactory.javaStringObjectInspector);

        //返回一个对象，该对象封装了列的名字以及列的类型
        return ObjectInspectorFactory.getStandardStructObjectInspector(colNames, colTypes);
    }


    /*
        输入：a,1,2,3,4,5,6,7,8,9,10,11,12
        输出：
            a 0时 1
            a 2时 2
            a 4时 3
            ..
            a 24时 12

     */
    @Override
    public void process(Object[] args) throws HiveException { //作用在每一行上的
        //创建一个数组，存储一行三列的数据
        String[] rows = new String[3];

        //因为接收了13列的数据，args的长度是13 索引最大值是12
        //第一列是监测点编号
        String id = args[0].toString();
        rows[0] = id;
        for (int i = 1, j = 0; i < args.length; i++, j += 2) {
            rows[1] = j + "时";
            rows[2] = args[i].toString();

            forward(rows);
        }
    }

    @Override
    public void close() throws HiveException {

    }
}
